package com.qigao.mall.channel.weichat;

import com.google.common.base.Charsets;
import com.qigao.mall.channel.ChannelCore;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.commons.dto.MerChannelDto;
import com.qigao.mall.commons.enums.ChannelActionEnum;
import com.qigao.mall.commons.enums.ChannelCodeEnum;
import com.qigao.mall.commons.enums.ChannelInfoEnum;
import com.qigao.mall.commons.enums.PayProductEnum;
import com.qigao.mall.commons.param.ChannelReqParam;
import com.qigao.mall.commons.param.ChannelRespParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 微信H5预登陆
 * https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
 */
@Service
public class WeichatOpenLogin implements ChannelCore {
    private static Logger logger= LoggerFactory.getLogger(WeichatOpenLogin.class);
    @Resource
    ChannelConstant channelConstant;

    @Override
    public boolean isSupport(PayProductEnum payProductEnum, ChannelActionEnum channelActionEnum, ChannelInfoEnum channelInfoEnum) {
        return ChannelActionEnum.PRE_LOGIN.equals(channelActionEnum) &&
                PayProductEnum.WEICHAT_PC_LOGIN.equals(payProductEnum)&&
                ChannelInfoEnum.WEICHAT.equals(channelInfoEnum)
                ;
    }

    @Override
    public ChannelRespParam channelProcess(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        String checkTokenUrl= null;
        try {
            checkTokenUrl = channelConstant.getWeichatOpenLoginUrl()+"?appid="+merChannelDto.getAppId()+"&redirect_uri="+ URLEncoder.encode(channelConstant.getWeichatAuthForwardUrl(), Charsets.UTF_8.name() )+"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // checkTokenUrl = channelConstant.getWeichatOpenLoginUrl()+"?appid="+merChannelDto.getAppId()+"&redirect_uri="+ channelConstant.getAuthForwardUrl()+"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        logger.info("[微信H5授权登录]请求地址:{}",checkTokenUrl);
        ChannelRespParam channelRespParam=new ChannelRespParam();
        channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
        channelRespParam.setRespMsg(ChannelCodeEnum.SUCCESS.getName());
        channelRespParam.setRespContent(checkTokenUrl);
        return channelRespParam;
    }
}
